package com.huai.demo_test1.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huai.demo_test1.pojo.Student;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author 淮晓欢
 * @date 2021/12/28
 **/
@RestController
@RequestMapping("/httpClientController")
@Slf4j
public class HttpClientController{
    @Resource
    private HttpClient httpClient;

    @GetMapping("/testGet")
    public String testGet() throws IOException {
        HttpGet httpGet=new HttpGet("http://localhost:8080/test/echo/1/淮晓欢");

        HttpResponse execute = httpClient.execute(httpGet);
        HttpEntity entity = execute.getEntity();
        return EntityUtils.toString(entity);
    }

    @PostMapping
    public Student testPost(@RequestBody Student student) throws IOException {
        HttpPost httpPost = new HttpPost("http://localhost:8080/test/echo/requestBody");

        ObjectMapper objectMapper=new ObjectMapper();
        //解决中文乱码问题，在后面设置编码
        StringEntity stringEntity = new StringEntity(objectMapper.writeValueAsString(student),StandardCharsets.UTF_8);
        httpPost.setEntity(stringEntity);
        httpPost.setHeader("Content-Type","application/json");
        HttpResponse execute = httpClient.execute(httpPost);
        String result = EntityUtils.toString(execute.getEntity(),"utf-8");
        Student value = objectMapper.readValue(result, Student.class);
        return value;
    }
}
